/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 *//*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.valstorm.mb;

import br.valstorm.facade.UserFacade;
import br.valstorm.model.User;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;

/**
 *
 * @author rgrunitzki
 */
@ManagedBean
@SessionScoped
public class UserMB extends AbstractMB implements Serializable {

    @EJB
    private UserFacade userFacade;

    private User user = new User();
    private List<User> users;

    @PostConstruct
    public void init() {
        user = new User();
    }

    public void cadNewUser(ActionEvent actionEvent) {
        if (user.getId() == 0) {
            try {
                closeDialog();
                userFacade.save(user);
                user = new User();
                displayInfoMessageToUser("Usuário cadastrado com sucesso");
            }catch(Exception e){
                displayErrorMessageToUser("Erro ao cadastrar usuário");
            }

        } else {
            user = userFacade.update(user);
        }

    }

    public void clear() {
        System.out.println("Limpar");
        user = new User();
    }

    public void remove() {
        userFacade.delete(user);
        user = new User();
    }

    public void loadUsers(ActionEvent event) {
        System.out.println("finding users");
        users = userFacade.findAll();
        System.out.println("Quantidade: " + users.size());
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

}
